package cn.zcy.conno;


import com.mysql.jdbc.JDBC4Connection;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 自定义连接对象
 * <p>
 * ，定义一个类，继承JDBC4Connection
 * 定义Connection连接对象和容器对象的成员
 * 通过有参方法给成员变量赋值
 * 重写close方法，完成归还连接
 */
public class MyConnection2 {
//    private Connection connection;
//
//    private List<Connection> pool;
//
//    public MyConnection2(Connection connection, List<Connection> pool) {
//        this.connection = connection;
//        this.pool = pool;
//    }

    public Connection getMyConnection2(Connection connection, ConcurrentLinkedQueue<Connection> pool) {
        Connection myConnection2 = (Connection) Proxy.newProxyInstance(connection.getClass().getClassLoader(), new Class<?>[]{Connection.class}, new InvocationHandler() {
            Object res = null;

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equalsIgnoreCase("close")) {
                    pool.offer(connection);
                    return null;
                } else {
                    res = method.invoke(connection, args);
                    return res;
                }
            }
        });
        return myConnection2;
    }

}
